package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.user.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {


    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 订单超时任务
     * 每分钟价格将超过15分钟且未付款的订单状态变更为已经取消
     */
    @Scheduled(cron = "30 * * * * ? ")
    public void orderTimeOut(){
        log.info("更新未付款订单状态");
        // 构建查询对象 状态和时间
        Orders orders = Orders.builder()
                .status(Orders.PENDING_PAYMENT)
                .orderTime(LocalDateTime.now().plusMinutes(-15))
                .build();
        List<Orders> ordersList = ordersMapper.selectTimeOut(orders);

        for (Orders orders1 : ordersList) {
            // 构建更新对象
            orders1.setStatus(Orders.CANCELLED);
            orders1.setCancelTime(LocalDateTime.now());
            orders1.setCancelReason(MessageConstant.ORDER_TIME_OUT);
            ordersMapper.update(orders1);
        }
    }

    /**
     * 每天晚上将状态为派送中但是实际已完成的订单的状态从4修改为5
     */
    @Scheduled(cron = "0 0 0 * * ?")
//    @Scheduled(cron = "0 * * * * ? ") 测试时使用
    public void deliveryStatus(){
        // 获取状态为4的订单
        List<Orders> orders = ordersMapper.selectById(null, null, null, Orders.DELIVERY_IN_PROGRESS);
        // 如果是已经超过到达时间就修改为5已完成
        for (Orders orders1 : orders) {
            if (orders1.getEstimatedDeliveryTime().isBefore(LocalDateTime.now())){
                log.info("更新派送中的订单状态为已完成");
                orders1.setStatus(Orders.COMPLETED);
                ordersMapper.update(orders1);
            }
        }
    }
}
